/**
 * @author gao
 * @date 2025/7/3 10:41
 */

public class Demo1 {
    public static void main(String[] args) throws InterruptedException {
        Object locker1 = new Object();
        Object locker2 = new Object();

        Thread t1 = new Thread(() -> {
            synchronized (locker1) {
                System.out.println("t1拿到了locker1");
                // 此处的sleep目的是让t1和t2分别获得对应的locker1和locker2
                // 如果t1和t2同时获得对应的locker1和locker2，那么t1和t2会互相等待对方释放锁，造成死锁
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (locker2) {
                    System.out.println("t1拿到了locker2");
                }
            }
        });

        Thread t2 = new Thread(() -> {
            synchronized (locker2) {
                System.out.println("t2拿到了locker2");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (locker1) {
                    System.out.println("t2拿到了locker1");
                }
            }
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();
    }
}